<template>
    <el-container class="admin-container">
      <!-- 搜索框 -->
      <el-header class="search-header">
        <el-row :gutter="20" justify="space-between" align="middle">
          <el-col :span="8">
            <el-input v-model="searchForm.adminName" placeholder="管理员名字" clearable>
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-input v-model="searchForm.phone" placeholder="电话" clearable>
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button plain icon="Refresh" @click="resetSearchForm">重置</el-button>
            <el-button plain icon="Plus" @click="handleAdd">新增超级用户</el-button>
          </el-col>
        </el-row>
      </el-header>
  
      <!-- 超级用户表格 -->
      <el-main class="main-content">
        <el-table
          :data="admins"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          :header-cell-style="{ background: '#f5f7fa' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="adminName" label="管理员名字" width="180" />
          <el-table-column prop="phone" label="电话" width="180" />
          <el-table-column label="头像" width="120">
            <template #default="{ row }">
              <el-avatar :src="row.avatar" size="small"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              <span>{{ formatDate(row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="240">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleDetail(scope.row)">详情</el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDeleteConfirm(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
  
      <!-- 弹窗组件 -->
      <el-dialog
        v-model="dialogVisible"
        :title="currentDialogType === 'add' ? '添加超级用户' : currentDialogType === 'edit' ? '编辑超级用户' : '超级用户详情'"
        :width="currentDialogType === 'detail' ? '80%' : '600px'"
        class="admin-dialog"
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="管理员名字" prop="adminName">
                <el-input v-model="form.adminName" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="form.phone" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" type="password" :disabled="currentDialogType === 'detail'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="头像" prop="avatar">
                <el-upload
                  v-if="currentDialogType !== 'detail'"
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                  <el-icon v-else><Plus /></el-icon>
                </el-upload>
                <div v-else class="avatar-container">
                  <img :src="form.avatar" class="avatar" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <span v-if="currentDialogType !== 'detail'">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleConfirmAction" :loading="submitLoading">
              确定
            </el-button>
          </span>
          <span v-else>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-container>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  
  // 响应式数据
  const admins = ref([]);
  const loading = ref(false);
  const dialogVisible = ref(false);
  const currentDialogType = ref('add');
  const formRef = ref(null);
  const submitLoading = ref(false);
  
  // 分页配置
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  
  // 搜索文本
  const searchForm = reactive({
    adminName: '',
    phone: ''
  });
  
  // 表单数据
  const form = reactive({
    id: null,
    adminName: '',
    password: '',
    phone: '',
    avatar: null,
    createTime: null
  });
  
  // 表单验证规则
  const rules = reactive({
    adminName: [{ required: true, message: '请输入管理员名字', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的电话号码', trigger: 'blur' }
    ],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
  });
  
  // 获取超级用户列表（模拟数据）
  const fetchAdmins = async () => {
    loading.value = true;
    try {
      // 模拟从后端获取数据
      admins.value = [
        {
          id: 1,
          adminName: 'admin1',
          password: 'password1',
          phone: '13800138000',
          avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64360288247c8d4721eapng.png',
          createTime: new Date().toISOString()
        },
        {
          id: 2,
          adminName: 'admin2',
          password: 'password2',
          phone: '13800138001',
          avatar: 'https://cube.elemecdn.com/0/88/03b44f4622db9f2999804f31fe19e9f7.png',
          createTime: new Date().toISOString()
        }
      ];
      total.value = admins.value.length;
    } catch (error) {
      console.error('获取超级用户列表失败:', error);
    } finally {
      loading.value = false;
    }
  };
  
  // 初始化
  onMounted(fetchAdmins);
  
  // 搜索栏图片
  const handleSearch = async () => {
    currentPage.value = 1;
    // 这里可以调用实际的搜索接口
    // await api.searchAdmins(searchForm);
    // 模拟搜索结果
    admins.value = admins.value.filter(item =>
      item.adminName.includes(searchForm.adminName) &&
      item.phone.includes(searchForm.phone)
    );
  };
  
  // 重置搜索表单
  const resetSearchForm = () => {
    searchForm.adminName = '';
    searchForm.phone = '';
    handleSearch();
  };
  
  // 新增超级用户
  const handleAdd = () => {
    currentDialogType.value = 'add';
    Object.assign(form, {
      id: null,
      adminName: '',
      password: '',
      phone: '',
      avatar: null,
      createTime: null
    });
    if (formRef.value) {
      formRef.value.resetFields();
    }
    dialogVisible.value = true;
  };
  
  // 编辑超级用户
  const handleEdit = (row) => {
    currentDialogType.value = 'edit';
    Object.assign(form, row);
    dialogVisible.value = true;
  };
  
  // 查看详情
  const handleDetail = (row) => {
    currentDialogType.value = 'detail';
    Object.assign(form, row);
    dialogVisible.value = true;
  };
  
  // 提交表单
  const handleConfirmAction = async () => {
    try {
      await formRef.value.validate();
      submitLoading.value = true;
      if (currentDialogType.value === 'add') {
        // await api.addAdmin(form);
        ElMessage.success('添加成功');
      } else {
        // await api.updateAdmin(form);
        ElMessage.success('更新成功');
      }
      dialogVisible.value = false;
      // await fetchAdmins();
    } catch (error) {
      console.error('提交表单失败:', error);
    } finally {
      submitLoading.value = false;
    }
  };
  
  // 删除确认
  const handleDeleteConfirm = (row) => {
    ElMessageBox.confirm(`确定删除该超级用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        // await api.deleteAdmin(row.id);
        ElMessage.success('删除成功');
        admins.value = admins.value.filter(item => item.id !== row.id);
      } catch (error) {
        console.error('删除超级用户失败:', error);
      }
    });
  };
  
  // 分页控制
  const handleSizeChange = (val) => {
    pageSize.value = val;
    // fetchAdmins();
  };
  
  const handleCurrentChange = (val) => {
    currentPage.value = val;
    // fetchAdmins();
  };
  
  // 格式化日期
  const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
  };
  
  // 头像上传相关
  const uploadUrl = 'https://run.mocky.io/v3/9d0f20d1-935a-4f59-99c1-898889e87099'; // 替换为实际的上传接口地址
  const uploadHeaders = { 'Content-Type': 'multipart/form-data' };
  
  const handleAvatarSuccess = (response, file) => {
    form.avatar = URL.createObjectURL(file.raw);
  };
  
  const beforeAvatarUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      ElMessage.error('只能上传图片文件!');
    }
    return isImage;
  };
  </script>
  
  <style scoped>
  .admin-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
  }
  
  .search-header {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .main-content {
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
  
  .admin-dialog {
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  }
  
  .dialog-form {
    padding: 24px;
  }
  
  .el-row {
    margin-bottom: 20px;
  }
  
  .el-col:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 768px) {
    .el-col {
      width: 100% !important;
    }
  }
  
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  
  .avatar-container {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;
    height: 100px;
  }
  </style>